<template>
  <div class="">
    <!-- 弹窗 -->
    <el-dialog v-model="store.examInsertOpen"  :show-close="false" append-to-body class="dialogClass" width="60%" top="30px" draggable overflow >
      <!--弹窗标题-->
      <template #header="{ close, titleId }">
        <div class="dialogHeader">
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px;" v-if="store.examBaseId===0">新增</span>
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px; " v-if="store.examBaseId!==0">修改</span>
          <el-icon style="font-size: 18px;margin-top: 14px;cursor: pointer" @click="closeDialog">
            <CloseBold/>
          </el-icon>
        </div>
      </template>
      <!--弹窗内容-->
      <template #default>
        <el-form class="role-form" ref="addExamFormRef" :rules="rules" :model="addExamData" style="max-height: 600px; overflow-y: auto;">
          <el-form-item label="考试名称" prop="examName" label-width="120px">
            <el-input v-model="addExamData.examName" placeholder="请输入考试名称"></el-input>
          </el-form-item>
          <el-form-item label="考试类型" prop="examType" label-width="120px" >
            <el-select v-model="addExamData.examType" placeholder="请选择考试类型" :disabled="store.examBaseId!==0">
              <el-option v-for="item in examTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试简介" prop="examDescription" label-width="120px">
            <el-input v-model="addExamData.examDescription" placeholder="请输入考试简介"></el-input>
          </el-form-item>
          <el-row :gutter="10" v-for="item in addExamData.examScore">
            <el-col :span="10">
              <el-form-item :label="item.label+'个数'" label-width="120px">
                <el-input-number  :min="0" v-model="item.num" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item :label="item.label+'分数'">
                <el-input-number :min="0" v-model="item.score" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label="item.label+'总分'">{{item.num*item.score}}</el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="总分" prop="total" label-width="120px">
            <el-input :disabled="true" v-model="total"></el-input>
          </el-form-item>
          <el-form-item label="考试须知" label-width="120px"  prop="examNotice">
            <RichTextEditor v-model:get-html="addExamData.examNotice" :height="'200px'"  placeholder="请输入考试须知" />
          </el-form-item>
        </el-form>

      </template>
      <!--弹窗底部-->
      <template #footer>
        <span class="myDialogFooter">
          <el-button class="el-button__default" @click="closeDialog">取 消</el-button>
          <el-button type="primary" class="el-button__primary" @click="addExamBaseInfo()" v-if="store.examBaseId===0">确认添加</el-button>
          <el-button type="primary" class="el-button__primary" @click="updateExamInfo()" v-if="store.examBaseId!==0">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {defineEmits, onMounted, reactive, ref, watch} from "vue";
import {CloseBold} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {userStore} from "@/stores/user/userStore.js";
import {addOrUpdateRole, getRoleInfoById, getRoles} from "@/api/role/index.js";
import {getDeptList} from "@/api/dept/index.js";
import {addOrUpdateUser, getUserInfoById} from "@/api/user/index.js";
import {examBaseStore} from "@/stores/question/examStore.js";
import RichTextEditor from "@/components/RichTextEditor.vue";
import {addExamBase, getExamBaseInfo, update} from "@/api/question/exam.js";
const addExamFormRef = ref()
const emit = defineEmits(['refresh'])
const userDept=ref([])
const value=ref(0)
const total=ref(0)
const score=ref(0)
const addExamData=ref({
  id:null,
  examName:'',
  examDescription:'',
  examNotice:null,
  examType:0,
  examScore:[
    {"key":"single", "label":"单选题", "num":0, "score":0},
    {"key":"multiple", "label":"多选题", "num":0, "score":0},
    {"key":"judgment", "label":"判断题", "num":0, "score":0},
    {"key":"fill", "label":"填空题", "num":0, "score":0},
    {"key":"essay", "label":"简答题", "num":0, "score":0}
  ],
})
const rules = reactive({
  examName: [
    { required: true, message: "考试名称不能为空", trigger: "blur" }
  ],
  examDescription: [
    { required: true, message: "考试简介不能为空", trigger: "blur" }
  ],
  examType: [
    { required: true, message: "考试类型不能为空", trigger: "blur" }
  ],
  examScore: [
    { required: true, message: "成绩分布不能为空", trigger: "blur" }
  ],
});
const examTypeList=ref([
  {value:0,label:"普通考试"},
  {value:1,label:"证书考试"},
])
const store=examBaseStore()
const examScore=ref()
const getTotal=(newVal)=>{
  //循环examStore，计算总分
  total.value=0
  for (let i = 0; i < newVal.length; i++) {
    total.value+=newVal[i].num*newVal[i].score
  }
}
watch(store,()=>{
  if (store.examBaseId!==0){
    initExamBaseInfo(store.examBaseId)
  }
})
watch(addExamData,(newVal)=>{
  getTotal(newVal.examScore)
}, { deep: true })

const addExamBaseInfo = async () => {
  const valid= await addExamFormRef.value.validate()
  if(valid) {
    try {
      const data={
        examName: addExamData.value.examName,
        examType: addExamData.value.examType,
        examDescription: addExamData.value.examDescription,
        examNotice:addExamData.value.examNotice,
        examScore: addExamData.value.examScore
      }
      const res = await addExamBase(data)
      ElMessage.success("添加成功")
      await closeDialog()
      emit('refresh')
    }catch (e){}
  }
}
const initExamBaseInfo=async (id) => {
  const res = await getExamBaseInfo(id);
  addExamData.value.examName = res.data.examName
  addExamData.value.examType = res.data.examType
  addExamData.value.examDescription = res.data.examDescription
  addExamData.value.examNotice = res.data.examNotice
  addExamData.value.examScore=res.data.examScore
  addExamData.value.id = res.data.id
}
const updateExamInfo =async () => {
  const valid= await addExamFormRef.value.validate()
  if(valid) {
    ElMessageBox.confirm(
        '是否继续修改考试信息?',
        '提示', {
          app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(async () => {
      const data={
        examName: addExamData.value.examName,
        examDescription: addExamData.value.examDescription,
        examNotice:addExamData.value.examNotice,
        examScore: addExamData.value.examScore,
        id:addExamData.value.id
      }
      const res =await update(data)
      if (res) {
        ElMessage.success("修改成功")
        await closeDialog()
      }
    }).catch(() => {
    })
  }
}
const  closeDialog = () => {
  store.setExamInsertOpen(false)
  store.setExamBaseId(0)
  addExamFormRef.value.resetFields()
  total.value=0
  addExamData.value={
    id:0,
    examName:'',
    examDescription:'',
    examNotice:'',
    examType:0,
    examScore:[
      {"key":"single", "label":"单选题", "num":0, "score":0},
      {"key":"multiple", "label":"多选题", "num":0, "score":0},
      {"key":"judgment", "label":"判断题", "num":0, "score":0},
      {"key":"fill", "label":"填空题", "num":0, "score":0},
      {"key":"judgment", "label":"简答题", "num":0, "score":0}
    ],
  }
  emit('refresh')
}
</script>

<style scoped>
.dialogClass{
  .el-dialog__body{
    min-height: 300px;
    max-height: 600px;
    overflow: auto;
  }
}

.el-dialog .el-dialog__header {
  margin: 0 !important;
  padding: 0 !important;
}

.el-dialog .dialogHeader {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  margin: 0 10px;
  font-size: 18px;
  font-weight: bolder;
}

/* 确保对话框主体可以使用flex布局 */
:deep(.el-dialog__body) {
  min-height: 300px !important;
  max-height: 600px !important;
  overflow: auto;
}

.role-form {
  margin:0  50px; /* 自动边距用于水平居中 */
  padding-right: 50px;
  overflow-x: hidden;
}

.el-dialog .el-dialog__footer {
  padding: 10px;
}

/* 统一选择框、数字框和输入框的宽度 */
.el-input,
.el-input-number,
.el-select,
.el-tree-select{
  --el-select-input-focus-border-color: rgb(46, 92, 246);
  --el-color-primary: rgb(46, 92, 246);
  width: 100%; /* 或者设置一个具体的像素值，比如240px */
  box-sizing: border-box; /* 确保内边距和边框包含在元素的总宽度和高度内 */
}
.el-date-picker{
  width: 80%;
}
.el-radio.is-bordered.is-checked {
  --el-color-primary: rgb(46, 92, 246);
}

.el-radio {
  --el-radio-input-border-color-hover: rgb(46, 92, 246);
}
</style>